/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.persistence.entity;

import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.ProcessEngineConfiguration;
import com.je.bpm.engine.impl.db.BulkDeleteable;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.je.bpm.engine.runtime.Job.DEFAULT_EXCLUSIVE;

/**
 * Abstract job entity class.
 */
public abstract class AbstractJobEntityImpl extends AbstractEntity implements AbstractJobEntity, BulkDeleteable, Serializable {

    private static final long serialVersionUID = 1L;

    protected Date duedate;

    protected String executionId;
    protected String processInstanceId;
    protected String processDefinitionId;

    protected boolean isExclusive = DEFAULT_EXCLUSIVE;

    protected int retries;

    protected int maxIterations;
    protected String repeat;
    protected Date endDate;

    protected String jobHandlerType;
    protected String jobHandlerConfiguration;

    protected ByteArrayRef exceptionByteArrayRef;
    protected String exceptionMessage;

    protected String tenantId = ProcessEngineConfiguration.NO_TENANT_ID;
    protected String jobType;

    @Override
    public Object getPersistentState() {
        Map<String, Object> persistentState = new HashMap<String, Object>();
        persistentState.put("retries", retries);
        persistentState.put("duedate", duedate);
        persistentState.put("exceptionMessage", exceptionMessage);

        if (exceptionByteArrayRef != null) {
            persistentState.put("exceptionByteArrayId", exceptionByteArrayRef.getId());
        }

        return persistentState;
    }

    // getters and setters ////////////////////////////////////////////////////////
    @Override
    public void setExecution(ExecutionEntity execution) {
        executionId = execution.getId();
        processInstanceId = execution.getProcessInstanceId();
        processDefinitionId = execution.getProcessDefinitionId();
    }

    @Override
    public Date getDuedate() {
        return duedate;
    }

    @Override
    public void setDuedate(Date duedate) {
        this.duedate = duedate;
    }

    @Override
    public String getExecutionId() {
        return executionId;
    }

    @Override
    public void setExecutionId(String executionId) {
        this.executionId = executionId;
    }

    @Override
    public int getRetries() {
        return retries;
    }

    @Override
    public void setRetries(int retries) {
        this.retries = retries;
    }

    @Override
    public String getProcessInstanceId() {
        return processInstanceId;
    }

    @Override
    public void setProcessInstanceId(String processInstanceId) {
        this.processInstanceId = processInstanceId;
    }

    @Override
    public boolean isExclusive() {
        return isExclusive;
    }

    @Override
    public void setExclusive(boolean isExclusive) {
        this.isExclusive = isExclusive;
    }

    @Override
    public String getProcessDefinitionId() {
        return processDefinitionId;
    }

    @Override
    public void setProcessDefinitionId(String processDefinitionId) {
        this.processDefinitionId = processDefinitionId;
    }

    @Override
    public String getRepeat() {
        return repeat;
    }

    @Override
    public void setRepeat(String repeat) {
        this.repeat = repeat;
    }

    @Override
    public Date getEndDate() {
        return endDate;
    }

    @Override
    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    @Override
    public int getMaxIterations() {
        return maxIterations;
    }

    @Override
    public void setMaxIterations(int maxIterations) {
        this.maxIterations = maxIterations;
    }

    @Override
    public String getJobHandlerType() {
        return jobHandlerType;
    }

    @Override
    public void setJobHandlerType(String jobHandlerType) {
        this.jobHandlerType = jobHandlerType;
    }

    @Override
    public String getJobHandlerConfiguration() {
        return jobHandlerConfiguration;
    }

    @Override
    public void setJobHandlerConfiguration(String jobHandlerConfiguration) {
        this.jobHandlerConfiguration = jobHandlerConfiguration;
    }

    @Override
    public String getJobType() {
        return jobType;
    }

    @Override
    public void setJobType(String jobType) {
        this.jobType = jobType;
    }

    @Override
    public String getTenantId() {
        return tenantId;
    }

    @Override
    public void setTenantId(String tenantId) {
        this.tenantId = tenantId;
    }

    @Override
    public String getExceptionStacktrace() {
        if (exceptionByteArrayRef == null) {
            return null;
        }

        byte[] bytes = exceptionByteArrayRef.getBytes();
        if (bytes == null) {
            return null;
        }

        try {
            return new String(bytes, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new ActivitiException("UTF-8 is not a supported encoding");
        }
    }

    @Override
    public void setExceptionStacktrace(String exception) {
        if (exceptionByteArrayRef == null) {
            exceptionByteArrayRef = new ByteArrayRef();
        }
        exceptionByteArrayRef.setValue("stacktrace", getUtf8Bytes(exception));
    }

    @Override
    public String getExceptionMessage() {
        return exceptionMessage;
    }

    @Override
    public void setExceptionMessage(String exceptionMessage) {
        this.exceptionMessage = StringUtils.abbreviate(exceptionMessage, MAX_EXCEPTION_MESSAGE_LENGTH);
    }

    @Override
    public ByteArrayRef getExceptionByteArrayRef() {
        return exceptionByteArrayRef;
    }

    protected byte[] getUtf8Bytes(String str) {
        if (str == null) {
            return null;
        }
        try {
            return str.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new ActivitiException("UTF-8 is not a supported encoding");
        }
    }

    @Override
    public String toString() {
        return getClass().getName() + " [id=" + id + "]";
    }

}
